package com.enhe.gck.exception;

import cn.hutool.json.JSONUtil;
import com.enhe.gck.communal.Resp;
import com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 抛出异常处理
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Resp<Object> businessException(BusinessException e) {
        log.error("业务异常={}", e.getMessage());
        return Resp.fail(e.getMessage());
    }

    @ExceptionHandler(WeighException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Resp<Object> weighException(WeighException e) {
        log.error("称重异常={}", e.getMessage());
        return Resp.weighFail(e.getWeighResultCode(), e.getMessage());
    }

    /**
     * 空指针处理
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Resp<Object> nullPointerException(NullPointerException e) {
        log.error("空指针异常", e);
        e.printStackTrace();
        return Resp.fail("空指针异常");
    }

    @ExceptionHandler(MySqlException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Resp<Object> mysqlException(MySqlException e) {
        log.error("数据库异常!原因:{}", e.getMessage());
        e.printStackTrace();
        return Resp.mysqlFail("数据库异常!");
    }

    @ExceptionHandler(MySQLTransactionRollbackException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Resp<Object> mysqlTransactionRollbackException(MySQLTransactionRollbackException e) {
        log.error("数据库操作异常!原因:{}", e.getMessage());
        e.printStackTrace();
        return Resp.mysqlFail("数据库操作异常!");
    }

    /**
     * 抛出异常处理
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Resp<Object> noException(Exception e) {
        log.error("未知异常={}", e.getMessage());
        e.printStackTrace();
        return Resp.fail(e.getMessage());
    }

}
